package cn.pubinfo.commentapi.service.impl;

import cn.pubinfo.commentapi.model.Tour;
import cn.pubinfo.commentapi.service.TourService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author kuancz
 * @date 2018/7/24
 */
@Service
public class TourServiceImpl implements TourService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(TourServiceImpl.class);

    @Override
    public List<Tour> list(String area, String category) {
        List<Tour> tourList = new ArrayList<>();
        Map<Object, Object> map = redisTemplate.opsForHash().entries(area + ":" + category);
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Integer id = Integer.parseInt(entry.getKey().toString());
            Tour tour = assemble(id, category, entry.getValue());
            tourList.add(tour);
        }
        return tourList;
    }

    @Override
    public Tour get(String area, String category, Integer id) {
        Object object = redisTemplate.opsForHash().get(area + ":" + category, String.valueOf(id));
        if (object == null){
            return null;
        }
        return assemble(id, category, object);
    }

    @Override
    public Long count(String area, String category) {
        String key = String.join(":", Arrays.asList(area, category));
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 装配tour对象
     *
     * @param category 种类，包括酒店、景点、旅行社
     * @param id tourId
     * @param info tour的redis信息
     * @return tour
     * @author kun
     * @date 2018-07-24
     */
    private Tour assemble(Integer id, String category, Object info){
        JSONObject jsonObject = JSONObject.parseObject(info.toString());
        Tour tour = JSON.toJavaObject(jsonObject, Tour.class);
        tour.setId(id);
        tour.setCategory(category);
        return tour;
    }

}
